package com.tjetc.dao.impl;

import com.tjetc.dao.NewsDao;
import com.tjetc.domain.News;
import com.tjetc.utils.Db;
import com.tjetc.utils.PageInfo;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class NewsDaoImpl implements NewsDao {

    @Override
    public List<News> findBySid(int sid) throws SQLException {
        return Db.runner0().query("select * from news where sid = ?",new BeanListHandler<>(News.class),sid);
    }

    @Override
    public List<News> listHotNews() throws SQLException {
        return Db.runner0().query("select * from news where sid = 1",new BeanListHandler<>(News.class));
    }

    @Override
    public int getCount(String content) throws SQLException {
        return ((Long)Db.runner0().query("select count(id) from news where content like ?",
                new ScalarHandler<>(),"%"+content+"%")).intValue();
    }

    @Override
    public List<News> list(String content, PageInfo<News> pageInfo) throws SQLException {
        return Db.runner0().query("select * from news where content like ? limit ?,?",
                new BeanListHandler<>(News.class),"%"+content+"%",
                pageInfo.getStartRecord(),pageInfo.getPageSize());
    }

    @Override
    public int del(int id) throws SQLException {
        return Db.runner0().update("delete from news where id=?",id);
    }

    @Override
    public int add(News news) throws SQLException {
        return Db.runner0().update("insert into news (content,sid) values(?,?)",
                news.getContent(),news.getSid());
    }

    @Override
    public int update(News news) throws SQLException {
        return Db.runner0().update("update news set content=?,sid=? where id=?",
                news.getContent(),news.getSid(),news.getId());
    }


}
